package net.lab1024.sa.admin.module.business.sendMsg.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.lab1024.sa.admin.module.business.contact.domain.form.ContactQueryForm;
import net.lab1024.sa.admin.module.business.contact.domain.vo.ContactVO;
import net.lab1024.sa.admin.module.business.contact.service.ContactService;
import net.lab1024.sa.base.common.annoation.NoNeedLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;

@RestController
public class SnmpController {
    @Autowired
    private ContactService contactService;
//
//    public SnmpController() {
//    }
//
//    @NoNeedLogin
//    @GetMapping({"/snmp/get"})
//    public String getSnmpValue(@RequestParam String ip, @RequestParam String community, @RequestParam String oid) {
//        try {
//            return this.snmpService.get(ip, community, oid);
//        } catch (IOException e) {
//            e.printStackTrace();
//            return "Error retrieving SNMP value";
//        }
//    }

    @NoNeedLogin
    @PostMapping({"/webhook"})
    public void handleWebhook(@RequestBody String payload) {
        System.out.println("Received webhook payload: " + payload);
        JSONObject json = JSON.parseObject(payload);
        String msg = json.getString("msg");
        List<ContactVO> list = contactService.list(new ContactQueryForm());
        String[] phones = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            phones[i] = list.get(i).getPhone();
        }

        if (!msg.contains("\ud83d\udd34 Down")){
            for(String phone : phones) {
                this.send(phone, msg);

                try {
                    Thread.sleep(3000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public void send(String phone, String msg) {
        String serverIp = "78.96.16.10";
        int serverPort = 20108;
        String message = "86" + phone + ":0:" + msg;
        message = message.replaceAll("\ud83d\udd34 Down", "离线");
        message = message.replaceAll("✅ Up", "在线");
        System.out.println(message);
        if (message.contains("离线")) {
            return;
        }

        try (Socket socket = new Socket(serverIp, serverPort)) {
            System.out.println("Connected to server at " + serverIp + ":" + serverPort);
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(message.getBytes("GBK"));
            outputStream.flush();
            socket.close();
            System.out.println("Message sent: " + message);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
